package com.utbm.lo54.controllers;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.utbm.lo54.dao.mysql.MysqlCourseDAO;
import com.utbm.lo54.dao.mysql.MysqlLocationDAO;
import com.utbm.lo54.dao.mysql.MysqlSessionDAO;
import com.utbm.lo54.entity.Course;
import com.utbm.lo54.entity.Location;
import com.utbm.lo54.entity.Session;

/**
 * Servlet implementation class SessionServlet
 */
@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MysqlCourseDAO courseDao = new  MysqlCourseDAO();
		MysqlSessionDAO sessionDAO = new MysqlSessionDAO();
		MysqlLocationDAO locationDAO = new MysqlLocationDAO();

		Course course = courseDao.findByCode((String)request.getParameter("course"));	
		Set<Session> sessions = sessionDAO.findByCourse(course.getCode());
		Hashtable<Long,Location> locations = new Hashtable<Long,Location>();
		Iterator<Session> ite = sessions.iterator();
		while(ite.hasNext()){
			Session session = (Session)ite.next();
			Location location = locationDAO.findById(session.getLocationId());
			if(!locations.containsKey(location.getId())){
				locations.put(location.getId(),location);
			}
		}
		
		request.setAttribute("sessions",sessions);
		request.setAttribute("locations",locations);
		request.setAttribute("course",course);

		RequestDispatcher dis=request.getRequestDispatcher("Session.jsp");
		dis.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
